package com.pp.demo.common.security;

import com.pp.demo.common.util.SignatureUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class AuthFilter extends OncePerRequestFilter {

    private final SecurityProperties securityProperties;

    private final AuthProperties authProperties;

    private final PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        log.info("请求路径: {}", requestURI);

        // 排除不需要认证的路径
        // 检查是否是忽略路径
        if (isIgnorePath(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 获取请求头中的认证信息
        String appId = request.getHeader("X-App-ID");
        String signature = request.getHeader("X-Signature");
        String timestamp = request.getHeader("X-Timestamp");
        String nonce = request.getHeader("X-Nonce");

        // 验证请求头是否完整
        if (!StringUtils.hasText(appId) || !StringUtils.hasText(signature) ||
                !StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce)) {
            sendErrorResponse(response, HttpStatus.UNAUTHORIZED, "缺少认证信息");
            return;
        }

        // 验证AppID是否有效
        if (!authProperties.isValidApp(appId)) {
            sendErrorResponse(response, HttpStatus.UNAUTHORIZED, "无效的AppID");
            return;
        }

        // 获取请求参数
        Map<String, String> params = new HashMap<>();
        request.getParameterMap().forEach((key, values) -> {
            if (values != null && values.length > 0) {
                params.put(key, values[0]);
            }
        });

        // 验证签名
        String secret = authProperties.getSecret(appId);
        if (!SignatureUtils.verifySignature(appId, secret, timestamp, nonce, signature, params)) {
            sendErrorResponse(response, HttpStatus.UNAUTHORIZED, "签名验证失败");
            return;
        }

        log.info("认证通过，继续处理请求 ----------->");
        // 创建认证对象
        Authentication authentication = new UsernamePasswordAuthenticationToken(appId, null, Collections.emptyList());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 认证通过，继续处理请求
        filterChain.doFilter(request, response);
    }

    /**
     * 检查请求路径是否在忽略列表中
     */
    private boolean isIgnorePath(String requestUri) {
        return securityProperties.getProcessedExcludedPaths().stream()
                .anyMatch(pattern -> pathMatcher.match(pattern, requestUri));
    }

    private void sendErrorResponse(HttpServletResponse response, HttpStatus status, String msg) throws IOException {
        response.setStatus(status.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":" + status.value() + ",\"msg\":\"" + msg + "\"}");
    }
}
